package com.qd.panda.service.invoice;

import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.hk.HkParkOrderDTO;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.common.panda.domain.entity.invoice.UserInvoiceDTO;
import com.qd.common.panda.domain.entity.invoice.UserInvoiceRecordsDTO;
import com.qd.panda.mapper.invoice.UserInvoiceRecordsMapper;
import com.qd.panda.model.HkParkOrder;
import com.qd.panda.model.UserInvoiceOrder;
import com.qd.panda.model.UserInvoiceRecords;
import com.qd.panda.service.hk.HkParkOrderService;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.login.LoginUserService;
import com.qd.system.service.org.OrgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 开票申请
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserInvoiceRecordsService extends BaseService<UserInvoiceRecordsMapper, UserInvoiceRecords> {

    private static final String PREFIX_ID = "panda_user_invoice_records_logId_{0}";

    private final RedisTemplateUtil<UserInvoiceRecords> redisTemplateUtil;
    private final LoginUserService loginUserService;
    private final OrgService orgService;
    private final UserInvoiceService userInvoiceService;
    private final UserInvoiceOrderService userInvoiceOrderService;
    private final HkParkOrderService hkParkOrderService;
    private final ObjectMapper objectMapper;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserInvoiceRecordsDTO save(UserInvoiceRecordsDTO dto) {
        dto.setLogId(IdWorker.getIdStr());
        validator(dto);
        final UserInvoiceRecords model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                saveUserInvoice(dto);
                saveUserInvoiceOrder(dto);
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserInvoiceRecordsDTO update(UserInvoiceRecordsDTO dto) {
        final UserInvoiceRecords historyModel = Optional.ofNullable(getById(dto.getLogId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserInvoiceRecords model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<UserInvoiceRecords> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<UserInvoiceRecords> mList) {
        final List<String> ids = mList.stream().map(UserInvoiceRecords::getLogId).collect(toList());
        final List<UserInvoiceRecords> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param logId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String logId) {
        final UserInvoiceRecords historyModel = Optional.ofNullable(getById(logId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        if (historyModel.getStatus() == 1) {
            throw new ApiException("已处理数据不能删除");
        }
        try {
            if (!super.removeById(logId)) {
                throw new ApiException("删除失败");
            }
            if (!userInvoiceOrderService.removeByLogId(logId)) {
                throw new ApiException("删除订单数据失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        ids.forEach(this::removeById);
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserInvoiceRecordsDTO dto) {
        final QueryWrapper<UserInvoiceRecords> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param logId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String logId) {
        boolean exists = false;
        if (StringUtils.hasLength(logId)) {
            final UserInvoiceRecords model = getById(logId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserInvoiceRecords getById(String logId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, logId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(logId), UserInvoiceRecords.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserInvoiceRecordsDTO getByIdDto(String logId) {
        return Optional.ofNullable(getById(logId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserInvoiceRecords getOne(UserInvoiceRecordsDTO dto) {
        final QueryWrapper<UserInvoiceRecords> queryWrapper = createQueryWrapper(dto);
        UserInvoiceRecords model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserInvoiceRecordsDTO getOneDto(UserInvoiceRecordsDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserInvoiceRecords> getList(UserInvoiceRecordsDTO dto) {
        final QueryWrapper<UserInvoiceRecords> queryWrapper = createQueryWrapper(dto);
        final List<UserInvoiceRecords> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserInvoiceRecordsDTO> getListDto(UserInvoiceRecordsDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserInvoiceRecordsDTO> page(Page<UserInvoiceRecords> page, UserInvoiceRecordsDTO dto) {
        final QueryWrapper<UserInvoiceRecords> queryWrapper = createQueryWrapper(dto, "");
        if (StringUtils.hasLength(dto.getUserId())) {
            queryWrapper.orderByDesc("add_time");
        }
        if (null != dto.getStatus()) {
            if (dto.getStatus() == 0) {
                queryWrapper.orderByAsc("add_time");
            }
            if (dto.getStatus() == 1) {
                queryWrapper.orderByAsc("process_time");
            }
        }
        final Page<UserInvoiceRecords> iPage = baseMapper.selectPage(page, queryWrapper);
        return iPage.convert(this::modelToDto);
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserInvoiceRecords model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLogId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserInvoiceRecords> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getLogId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserInvoiceRecordsDTO modelToDto(UserInvoiceRecords model) {
        if (null == model) {
            return null;
        }
        final UserInvoiceRecordsDTO dto = new UserInvoiceRecordsDTO();
        dto.setLogId(model.getLogId());
        dto.setTitle(model.getTitle());
        dto.setDutyParagraph(model.getDutyParagraph());
        dto.setNote(model.getNote());
        dto.setAmount(model.getAmount());
        dto.setMoreMsg(model.getMoreMsg());
        dto.setMobile(model.getMobile());
        dto.setEmail(model.getEmail());
        dto.setAddTime(model.getAddTime());
        dto.setProcessTime(model.getProcessTime());
        dto.setStatus(model.getStatus());
        dto.setOrderNumber(model.getOrderNumber());
        dto.setUserId(model.getUserId());
        dto.setHandlePersonId(model.getHandlePersonId());
        dto.setHandleOrgId(model.getHandleOrgId());
        dto.setTypeHeader(model.getTypeHeader());
        dto.setMsgType(model.getMsgType());
        dto.setRemarks(model.getRemarks());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserInvoiceRecords dtoToModel(UserInvoiceRecordsDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserInvoiceRecords model = new UserInvoiceRecords();
        model.setLogId(dto.getLogId());
        model.setTitle(dto.getTitle());
        model.setDutyParagraph(dto.getDutyParagraph());
        model.setNote(dto.getNote());
        model.setAmount(dto.getAmount());
        model.setMoreMsg(dto.getMoreMsg());
        model.setMobile(dto.getMobile());
        model.setEmail(dto.getEmail());
        model.setAddTime(dto.getAddTime());
        model.setProcessTime(dto.getProcessTime());
        model.setStatus(dto.getStatus());
        model.setOrderNumber(dto.getOrderNumber());
        model.setUserId(dto.getUserId());
        model.setHandlePersonId(dto.getHandlePersonId());
        model.setHandleOrgId(dto.getHandleOrgId());
        model.setTypeHeader(dto.getTypeHeader());
        model.setMsgType(dto.getMsgType());
        model.setRemarks(dto.getRemarks());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserInvoiceRecordsDTO dto) {
        dto.setTypeHeaderDisplay(MbUtil.idToDisplay(dto.getTypeHeader()));
        dto.setMsgTypeDisplay(MbUtil.idToDisplay(dto.getMsgType()));
        if (null != dto.getStatus()) {
            if (dto.getStatus() == 0) {
                dto.setStatusDisplay("已申请");
            }
            if (dto.getStatus() == 1) {
                dto.setStatusDisplay("已处理");
            }
            if (dto.getStatus() == 2) {
                dto.setStatusDisplay("已驳回");
            }
        }
        if (StringUtils.hasLength(dto.getHandleOrgId())) {
            dto.setHandleOrgIdDisplay(orgService.idToDisplay(dto.getHandleOrgId()));
        }
        if (StringUtils.hasLength(dto.getHandlePersonId())) {
            dto.setHandlePersonIdDisplay(loginUserService.idToDisplay(dto.getHandlePersonId()));
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserInvoiceRecordsDTO> modelToDtoList(List<UserInvoiceRecords> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserInvoiceRecords> dtoToModelList(List<UserInvoiceRecordsDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserInvoiceRecords> createQueryWrapper(UserInvoiceRecordsDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserInvoiceRecords> createQueryWrapper(UserInvoiceRecordsDTO dto, String tableAlias) {
        final QueryWrapper<UserInvoiceRecords> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getTitle())) {
                queryWrapper.like(tableAlias + "title", dto.getTitle());
            }
            if (StringUtils.hasLength(dto.getDutyParagraph())) {
                queryWrapper.eq(tableAlias + "duty_paragraph", dto.getDutyParagraph());
            }
            if (StringUtils.hasLength(dto.getMobile())) {
                queryWrapper.eq(tableAlias + "mobile", dto.getMobile());
            }
            if (StringUtils.hasLength(dto.getEmail())) {
                queryWrapper.eq(tableAlias + "email", dto.getEmail());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (StringUtils.hasLength(dto.getHandlePersonId())) {
                queryWrapper.eq(tableAlias + "handle_person_id", dto.getHandlePersonId());
            }
            if (StringUtils.hasLength(dto.getHandleOrgId())) {
                queryWrapper.eq(tableAlias + "handle_org_id", dto.getHandleOrgId());
            }
            if (StringUtils.hasLength(dto.getTypeHeader())) {
                queryWrapper.eq(tableAlias + "type_header", dto.getTypeHeader());
            }
            if (StringUtils.hasLength(dto.getMsgType())) {
                queryWrapper.eq(tableAlias + "msg_type", dto.getMsgType());
            }
            if (null != dto.getStatus()) {
                queryWrapper.eq(tableAlias + "status", dto.getStatus());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserInvoiceRecords> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserInvoiceRecords> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserInvoiceRecords::getLogId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    private void validator(UserInvoiceRecordsDTO dto) {
        if (StringUtils.hasLength(dto.getMsgType())) {
            if (!dto.getMsgType().equals(PandaConstant.MSG_TYPE_2)) {
                throw new ApiException("不支持的消息类型");
            }
        }
        if (StringUtils.hasLength(dto.getTypeHeader())) {
            if (MbUtil.isNotExists(dto.getTypeHeader(), BaseTableEnum.TYPE_HEADER)) {
                throw new ApiException("发票抬头类型值错误");
            }
            if (dto.getTypeHeader().equals(PandaConstant.TYPE_HEADER_1)) {
                if (!StringUtils.hasLength(dto.getDutyParagraph())) {
                    throw new ApiException("税号不能为空");
                }
            }
        }
        if (StringUtils.hasLength(dto.getSaveTemplate()) && MbUtil.isNotExists(dto.getSaveTemplate(), BaseTableEnum.SF)) {
            throw new ApiException("是否保存模版值错误");
        }
        List<String> orderIds = dto.getOrderIds();
        if (null == orderIds || orderIds.isEmpty()) {
            throw new ApiException("订单列表为空");
        }
        List<UserInvoiceOrder> list = userInvoiceOrderService.getListByIds(orderIds);
        if (!list.isEmpty()) {
            for (UserInvoiceOrder userInvoiceOrder : list) {
                log.error("当前订单已开票,订单ID: {}", userInvoiceOrder.getOrderId());
            }
            throw new ApiException("当前订单已开票,请勿重复操作");
        }
        if (dto.getMsgType().equals(PandaConstant.MSG_TYPE_2)) {
            List<HkParkOrder> hkParkOrders = hkParkOrderService.getListByUserIdAndOrderLogIds(dto.getUserId(), dto.getOrderIds());
            if (hkParkOrders.isEmpty() || hkParkOrders.size() != orderIds.size()) {
                throw new ApiException("订单信息有误");
            }
            BigDecimal amountYuan = hkParkOrders.stream().map(HkParkOrder::getPayMoney).reduce(Integer::sum).map(amount -> new Money(0, amount)).map(Money::getAmount).orElse(new BigDecimal("0.00"));
            dto.setAmount(amountYuan);
            dto.setOrderNumber(dto.getOrderIds().size());
        }
        dto.setStatus(0);
    }

    private void saveUserInvoiceOrder(UserInvoiceRecordsDTO dto) {
        List<UserInvoiceOrder> list = new ArrayList<>(dto.getOrderIds().size());
        for (String orderId : dto.getOrderIds()) {
            UserInvoiceOrder userInvoiceOrder = new UserInvoiceOrder();
            userInvoiceOrder.setOrderId(orderId);
            userInvoiceOrder.setLogId(dto.getLogId());
            list.add(userInvoiceOrder);
        }
        userInvoiceOrderService.saveBatch(list);
        list.clear();
    }

    private void saveUserInvoice(UserInvoiceRecordsDTO dto) {
        LocalDateTime now = Optional.ofNullable(dto.getAddTime()).orElse(LocalDateTime.now());
        if (!StringUtils.hasLength(dto.getSaveTemplate())) {
            return;
        }
        String userInvoiceId = dto.getUserInvoiceId();
        if (StringUtils.hasLength(userInvoiceId)) {
            UserInvoiceDTO invoiceDTO = Optional.ofNullable(userInvoiceService.getByIdDto(userInvoiceId)).orElseThrow(() -> new ApiException("个人开票ID值错误"));
            buildInvoiceDTO(dto, invoiceDTO);
            invoiceDTO.setUpdateTime(now);
            userInvoiceService.update(invoiceDTO);
            invoiceDTO.freeData();
        } else {
            UserInvoiceDTO invoiceDTO = new UserInvoiceDTO();
            buildInvoiceDTO(dto, invoiceDTO);
            invoiceDTO.setAddTime(now);
            userInvoiceService.save(invoiceDTO);
            invoiceDTO.freeData();
        }
    }

    private static void buildInvoiceDTO(UserInvoiceRecordsDTO dto, UserInvoiceDTO invoiceDTO) {
        invoiceDTO.setUserId(dto.getUserId());
        invoiceDTO.setTypeHeader(dto.getTypeHeader());
        invoiceDTO.setTitle(dto.getTitle());
        invoiceDTO.setDutyParagraph(dto.getDutyParagraph());
        invoiceDTO.setMobile(dto.getMobile());
        invoiceDTO.setEmail(dto.getEmail());
    }

    @Transactional(rollbackFor = Exception.class)
    public void handle(UserInvoiceRecordsDTO dto) {
        UserInvoiceRecordsDTO userInvoiceRecordsDTO = Optional.ofNullable(getByIdDto(dto.getLogId())).orElseThrow(() -> new ApiException("申请ID值错误"));
        if (userInvoiceRecordsDTO.getStatus() == 1 || userInvoiceRecordsDTO.getStatus() == 2) {
            throw new ApiException("请勿重复处理");
        }
        userInvoiceRecordsDTO.setStatus(dto.getStatus());
        if (StringUtils.hasLength(dto.getRemarks())) {
            userInvoiceRecordsDTO.setRemarks(dto.getRemarks());
        }
        userInvoiceRecordsDTO.setHandlePersonId(SecurityUtils.getLoginUser().getUserId());
        userInvoiceRecordsDTO.setHandleOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        userInvoiceRecordsDTO.setProcessTime(LocalDateTime.now());
        update(userInvoiceRecordsDTO);
        userInvoiceRecordsDTO.freeData();
    }

    @Transactional(readOnly = true)
    public ObjectNode orderList(String logId) {
        UserInvoiceRecords userInvoiceRecords = Optional.ofNullable(getById(logId)).orElseThrow(() -> new ApiException("记录ID值错误"));
        if (!userInvoiceRecords.getMsgType().equals(PandaConstant.MSG_TYPE_2)) {
            throw new ApiException("不支持的消息类型");
        }
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("logId", logId);
        objectNode.put("msgType", userInvoiceRecords.getMsgType());
        List<HkParkOrderDTO> list = hkParkOrderService.getBaseMapper().list(logId);
        objectNode.putPOJO("orderList", list);
        return objectNode;
    }
}